

import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import Animated, { useSharedValue, useAnimatedStyle, withSpring, withSequence, withTiming } from 'react-native-reanimated';
import styles from './styles';

interface ApprovalData {
  number: string;
  type: string;
  title: string;
}

interface ResultConfig {
  title: string;
  description: string;
  icon: string;
  iconClass: 'success' | 'error';
  resultText: string;
  resultClass: 'success' | 'error' | 'warning';
  tips: string[];
}

const ApprovalProcessScreen: React.FC = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  
  const [approvalData, setApprovalData] = useState<ApprovalData>({
    number: 'AP-20240101-001',
    type: '员工请假申请',
    title: '李小明的年假申请'
  });
  
  const [resultConfig, setResultConfig] = useState<ResultConfig>({
    title: '审批已通过',
    description: '您的审批操作已成功提交，流程将自动流转至下一节点处理。',
    icon: 'check',
    iconClass: 'success',
    resultText: '已通过',
    resultClass: 'success',
    tips: [
      '• 审批结果已实时同步到系统',
      '• 相关人员将收到审批状态通知',
      '• 您可以随时查看审批进度'
    ]
  });

  // 动画值
  const iconScale = useSharedValue(0.3);
  const iconOpacity = useSharedValue(0);
  const shakeX = useSharedValue(0);

  // 模拟审批数据
  const mockApprovalData: Record<string, ApprovalData> = {
    'AP-20240101-001': {
      number: 'AP-20240101-001',
      type: '员工请假申请',
      title: '李小明的年假申请'
    },
    'AP-20240101-002': {
      number: 'AP-20240101-002',
      type: '采购申请单',
      title: '办公设备采购申请'
    },
    'AP-20240101-003': {
      number: 'AP-20240101-003',
      type: '差旅报销申请',
      title: '赵销售的差旅费用报销'
    }
  };

  // 处理结果配置
  const resultConfigs: Record<string, ResultConfig> = {
    'approve': {
      title: '审批已通过',
      description: '您的审批操作已成功提交，流程将自动流转至下一节点处理。',
      icon: 'check',
      iconClass: 'success',
      resultText: '已通过',
      resultClass: 'success',
      tips: [
        '• 审批结果已实时同步到系统',
        '• 相关人员将收到审批状态通知',
        '• 您可以随时查看审批进度'
      ]
    },
    'reject': {
      title: '审批已驳回',
      description: '您的驳回操作已成功提交，流程将退回至发起人重新处理。',
      icon: 'times',
      iconClass: 'error',
      resultText: '已驳回',
      resultClass: 'error',
      tips: [
        '• 驳回原因已通知发起人',
        '• 发起人可以修改后重新提交',
        '• 您可以查看驳回历史记录'
      ]
    },
    'transfer': {
      title: '转办成功',
      description: '审批任务已成功转交给指定处理人，他们将收到待办通知。',
      icon: 'share-alt',
      iconClass: 'success',
      resultText: '已转办',
      resultClass: 'warning',
      tips: [
        '• 转办信息已通知接收人',
        '• 您可以跟踪转办后的处理进度',
        '• 转办记录已保存到系统'
      ]
    },
    'return': {
      title: '退回成功',
      description: '审批任务已成功退回至上一节点，相关处理人将收到通知。',
      icon: 'undo',
      iconClass: 'success',
      resultText: '已退回',
      resultClass: 'warning',
      tips: [
        '• 退回原因已通知相关人员',
        '• 上一节点处理人将重新处理',
        '• 退回记录已保存到系统'
      ]
    },
    'addSign': {
      title: '加签成功',
      description: '审批任务已成功添加加签人，加签人将收到待办通知。',
      icon: 'user-plus',
      iconClass: 'success',
      resultText: '已加签',
      resultClass: 'warning',
      tips: [
        '• 加签信息已通知相关人员',
        '• 加签人处理后流程将继续',
        '• 加签记录已保存到系统'
      ]
    },
    'delegate': {
      title: '委派成功',
      description: '审批任务已成功委派给指定处理人，他们将收到待办通知。',
      icon: 'user-tie',
      iconClass: 'success',
      resultText: '已委派',
      resultClass: 'warning',
      tips: [
        '• 委派信息已通知接收人',
        '• 被委派人将代替您处理此任务',
        '• 委派记录已保存到系统'
      ]
    },
    'cancel': {
      title: '取消成功',
      description: '审批任务已成功取消，流程将终止。',
      icon: 'ban',
      iconClass: 'error',
      resultText: '已取消',
      resultClass: 'error',
      tips: [
        '• 取消信息已通知相关人员',
        '• 流程已终止，无法继续',
        '• 取消记录已保存到系统'
      ]
    },
    'error': {
      title: '操作失败',
      description: '很抱歉，您的操作未能成功提交，请稍后重试或联系系统管理员。',
      icon: 'exclamation-triangle',
      iconClass: 'error',
      resultText: '失败',
      resultClass: 'error',
      tips: [
        '• 请检查网络连接后重试',
        '• 如问题持续存在，请联系IT支持',
        '• 您可以重新进入审批页面操作'
      ]
    }
  };

  useEffect(() => {
    // 获取当前操作和审批实例ID
    const action = (params.action as string) || 'approve';
    const processInstanceId = (params.processInstanceId as string) || 'AP-20240101-001';

    // 获取对应的配置
    const config = resultConfigs[action] || resultConfigs['approve'];
    const data = mockApprovalData[processInstanceId] || mockApprovalData['AP-20240101-001'];

    setApprovalData(data);
    setResultConfig(config);

    // 启动动画
    if (config.iconClass === 'success') {
      // 成功动画
      iconScale.value = withSequence(
        withSpring(1.05, { duration: 300 }),
        withSpring(0.9, { duration: 200 }),
        withSpring(1, { duration: 100 })
      );
      iconOpacity.value = withTiming(1, { duration: 600 });
    } else {
      // 错误动画
      shakeX.value = withSequence(
        withTiming(-10, { duration: 60 }),
        withTiming(10, { duration: 60 }),
        withTiming(-10, { duration: 60 }),
        withTiming(10, { duration: 60 }),
        withTiming(-10, { duration: 60 }),
        withTiming(10, { duration: 60 }),
        withTiming(0, { duration: 60 })
      );
      iconOpacity.value = withTiming(1, { duration: 600 });
    }
  }, [params]);

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleBackToListPress = () => {
    router.push('/p-pending_approval');
  };

  const handleViewDetailPress = () => {
    router.push(`/p-approval_detail?processInstanceId=${approvalData.number}`);
  };

  const getCurrentTime = () => {
    return new Date().toLocaleString('zh-CN');
  };

  const getResultIconStyle = () => {
    return resultConfig.iconClass === 'success' ? styles.successIcon : styles.errorIcon;
  };

  const getResultTextStyle = () => {
    switch (resultConfig.resultClass) {
      case 'success':
        return styles.successText;
      case 'error':
        return styles.errorText;
      case 'warning':
        return styles.warningText;
      default:
        return styles.successText;
    }
  };

  // 动画样式
  const iconAnimatedStyle = useAnimatedStyle(() => {
    return {
      transform: [
        { scale: iconScale.value },
        { translateX: shakeX.value }
      ],
      opacity: iconOpacity.value,
    };
  });

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
          <FontAwesome6 name="arrow-left" size={18} color="#D1D5DB" />
          <Text style={styles.backButtonText}>返回</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>审批结果</Text>
        <View style={styles.headerPlaceholder} />
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 主要内容区域 */}
        <View style={styles.mainContent}>
          {/* 结果展示区域 */}
          <View style={styles.resultContainer}>
            {/* 结果图标 */}
            <Animated.View style={[styles.resultIcon, getResultIconStyle(), iconAnimatedStyle]}>
              <FontAwesome6 name={resultConfig.icon} size={48} color="#FFFFFF" />
            </Animated.View>
            
            {/* 结果标题 */}
            <Text style={styles.resultTitle}>{resultConfig.title}</Text>
            
            {/* 结果说明 */}
            <Text style={styles.resultDescription}>{resultConfig.description}</Text>
            
            {/* 审批信息卡片 */}
            <LinearGradient
              colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.approvalInfoCard}
            >
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>审批单号</Text>
                <Text style={styles.infoValue}>{approvalData.number}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>审批类型</Text>
                <Text style={styles.infoValue}>{approvalData.type}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>处理时间</Text>
                <Text style={styles.infoValue}>{getCurrentTime()}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>处理结果</Text>
                <Text style={[styles.infoValue, getResultTextStyle()]}>{resultConfig.resultText}</Text>
              </View>
            </LinearGradient>
          </View>

          {/* 操作按钮区域 */}
          <View style={styles.actionButtons}>
            <TouchableOpacity style={styles.primaryButton} onPress={handleBackToListPress}>
              <LinearGradient
                colors={['#6366F1', '#8B5CF6']}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
                style={styles.primaryButtonGradient}
              >
                <FontAwesome6 name="list" size={16} color="#FFFFFF" />
                <Text style={styles.primaryButtonText}>返回待办列表</Text>
              </LinearGradient>
            </TouchableOpacity>
            
            <TouchableOpacity style={styles.secondaryButton} onPress={handleViewDetailPress}>
              <FontAwesome6 name="eye" size={16} color="#FFFFFF" />
              <Text style={styles.secondaryButtonText}>查看审批详情</Text>
            </TouchableOpacity>
          </View>

          {/* 提示信息 */}
          <View style={styles.tipsSection}>
            <View style={styles.tipsHeader}>
              <FontAwesome5 name="info-circle" size={18} color="#6366F1" />
              <Text style={styles.tipsTitle}>温馨提示</Text>
            </View>
            <View style={styles.tipsList}>
              {resultConfig.tips.map((tip, index) => (
                <Text key={index} style={styles.tipItem}>{tip}</Text>
              ))}
            </View>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default ApprovalProcessScreen;

